package cn.hrms.interception;

import cn.dev33.satoken.stp.StpUtil;
import cn.hrms.constant.HttpStatus;
import cn.hrms.domain.web.R;
import cn.hrms.utils.JsonUtils;
import cn.hrms.utils.ServletUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Token 拦截器
 * @author xiaokai
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class TokenInterceptor implements HandlerInterceptor {
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		// 判断当前拦截到的是Controller的方法还是其他资源
		if (!(handler instanceof HandlerMethod)) {
			// 当前拦截到的不是动态方法，直接放行
			return true;
		}

		// 获取请求url
		String url = request.getMethod() + " " + request.getRequestURI();
		log.info("开始请求 => URL[{}],", url);

		// 获取请求头中token
		String token = request.getHeader("Authorization");

		// 判断token 是否存在
		if (!StringUtils.hasText(token)) {
			ServletUtils.renderString(response, JsonUtils.toJsonString(R.fail(HttpStatus.UNAUTHORIZED, "未携带token")));
			return false;
		}

		// 解析token
		StpUtil.updateLastActiveToNow();
		return true;
	}
}
